# coding:utf-8
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, HttpResponse, redirect
import hashlib
from time import time
from xml.etree import ElementTree
from django.views.decorators.csrf import csrf_exempt
from django.views import View
from msg import receive, reply
from utils.basic import Basic
from utils.menu import Menu


class Handle(View):

    def token_validate(self, request):
        signature = request.GET.get('signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        hashstr = hashlib.sha1(
            ''.join(sorted([TOKEN, timestamp, nonce]))).hexdigest()
        if hashstr == signature:
            return True
        return False

    @csrf_exempt
    def get(self, request):
        """
        正确响应微信服务器发送的Token验证。
        :rtype: object
        :param request: 微信服务器发来的Token验证请求
        :return: 如果验证通过，将微信服务器请求中的echostr返回给微信服务器。
        """
        print "begin get"
        if request.GET.get('echostr') is not None:
            if self.token_validate(request):
                return HttpResponse(request.GET.get('echostr'))
            else:
                return HttpResponse("")

    @csrf_exempt
    def post(self, request):

        message_xml = request.read()
        root = ElementTree.fromstring(message_xml)
        form_user_name = root.find('FromUserName').text
        to_user_name = root.find('ToUserName').text
        message_type = root.find('MsgType').text

        context = {'to_user_name': form_user_name,
                   'from_user_name': to_user_name}
        if message_type == 'text':
            content = root.find('Content').text
            if content.lower() == 'l':
                reply_xml = self.generate_text_reply_xml(
                    request, context, type='history')
            elif content.lower() == 'h':
                reply_xml = self.generate_text_reply_xml(
                    request, context, type='help')
            else:
                context.update({'content': content})
                reply_xml = self.generate_text_reply_xml(request, context)
            return HttpResponse(reply_xml, content_type='application/xml; charset=utf-8')

    def generate_text_reply_xml(self,request, context, type='adjust'):
        text_xml = '''<xml>
               <ToUserName><![CDATA[%s]]></ToUserName>
               <FromUserName><![CDATA[%s]]></FromUserName>
               <CreateTime><![CDATA[%s]]></CreateTime>
               <MsgType><![CDATA[%s]]></MsgType>
               <Content><![CDATA[%s]]></Content>
               </xml>
           '''
        message_type = 'text'
        if type == 'greet' or type == 'help':
            content = '''查看个人信息，请回复1/:hug，
            '''
        else:
            content = '''good'''
        create_time = int(time())
        c = {
            'to_user_name': context['to_user_name'],
            'from_user_name': context['from_user_name'],
            'create_time': create_time,
            'message_type': message_type,
            'content': content
        }
        print "-----------------------------------"
        print c
        text_reply_xml = text_xml % (
            c['to_user_name'], c['from_user_name'], c['create_time'], c['message_type'], c['content'])

        return text_reply_xml


TOKEN = "gavin"


def token_validate(request):
    """
    通过token验证，确定请求信息是否来源于微信服务器，如果是，返回True，否则返回False。
    :param request: 微信服务器发来的请求。
    :return: 返回True  or False。
    """
    signature = request.GET.get('signature')  # 微信服务器的签名，是一个哈希字符串
    timestamp = request.GET.get('timestamp')  # 时间戳
    nonce = request.GET.get('nonce')
    hashstr = hashlib.sha1(
        ''.join(sorted([TOKEN, timestamp, nonce]))).hexdigest()  # 生成一个哈希字符串
    if hashstr == signature:
        return True
    return False


@csrf_exempt
def weixin(request):
    if request.method == 'GET':
        """
        正确响应微信服务器发送的Token验证。
        :param request: 微信服务器发来的Token验证请求
        :return: 如果验证通过，将微信服务器请求中的echostr返回给微信服务器。
        """
        if request.GET.get('echostr') is not None:
            if token_validate(request):  # 如果是微信发来的请求，将请求中echostr参数的值原样返回给微信服务器。
                return HttpResponse(request.GET.get('echostr'))
            raise PermissionDenied  # 否则抛出一个PermissionDenied类型的异常。
    message_xml = request.read()
    print "The message from weixin server is :\n", message_xml
    root = ElementTree.fromstring(message_xml)  # 将微信发来的xml信息格式化
    form_user_name = root.find('FromUserName').text  # 从xml中提取FromUserName的值
    to_user_name = root.find('ToUserName').text  # 从xml中提取ToUserName的值
    message_type = root.find('MsgType').text  # 从xml中提取MsgType的值
    print """after formstring,
    form_user_name is:%s,
    to_user_name is :%s,
    """ % (form_user_name, to_user_name)

    context = {'to_user_name': form_user_name, 'from_user_name': to_user_name}
    if message_type == 'text':  # 如果发来的是文本信息，按文本信息处理
        content = root.find('Content').text  # 从xml中提取Content的值
        if content.lower() == 'l':  # 忽略大小写
            reply_xml = generate_text_reply_xml(
                request, context, type='history')
        elif content.lower() == 'h':
            reply_xml = generate_text_reply_xml(request, context, type='help')
        else:
            context.update({'content': content})
            reply_xml = generate_text_reply_xml(request, context)
        return HttpResponse(reply_xml, content_type='application/xml; charset=utf-8')


def generate_text_reply_xml(request, context, type='adjust'):
    text_xml = '''<xml>
           <ToUserName><![CDATA[%s]]></ToUserName>
           <FromUserName><![CDATA[%s]]></FromUserName>
           <CreateTime><![CDATA[%s]]></CreateTime>
           <MsgType><![CDATA[%s]]></MsgType>
           <Content><![CDATA[%s]]></Content>
           </xml>
       '''
    message_type = 'text'
    if type == 'greet' or type == 'help':
        content = '''查看个人信息，请回复1/:hug，
        '''
    else:
        content = '''good'''
    create_time = 1359036631
    c = {
        'to_user_name': context['to_user_name'],
        'from_user_name': context['from_user_name'],
        'create_time': create_time,
        'message_type': message_type,
        'content': content
    }
    print "-----------------------------------"
    print c
    text_reply_xml = text_xml % (
        c['to_user_name'], c['from_user_name'], c['create_time'], c['message_type'], c['content'])

    return text_reply_xml





def WeChat(request):
    pass
